package de.shortys.myhome.api.model;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.parsers.ParserConfigurationException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.SAXException;

import de.java.shortys.utils.file.FileUtils;

public class DataHolderDescription {

	private List<String> attributeNames;
	private Map<String, Class<? extends Object>> types;
	private Map<String, Boolean> notNullables;

	{
		attributeNames = new ArrayList<String>();
		types = new TreeMap<String, Class<? extends Object>>();
		notNullables = new TreeMap<String, Boolean>();
	}

	public DataHolderDescription(String path) throws SAXException, IOException, ParserConfigurationException,
			ClassNotFoundException {
		initialize(path);
	}

	public Class<? extends Object> getType(String attributeId) {
		return types.get(attributeId);
	}

	public Boolean isNullable(String attributeId) {
		return !notNullables.get(attributeId);
	}

	@SuppressWarnings("unchecked")
	private void initialize(String path) throws SAXException, IOException, ParserConfigurationException,
			ClassNotFoundException {
		Document doc = null;

		File f = FileUtils.getFileFromClassPath(getClass().getClassLoader(), path);
		try {
			SAXBuilder builder = new SAXBuilder();
			doc = builder.build(f);
			Element root = doc.getRootElement();
			for (Element child : (List<Element>) root.getChildren()) {
				String attributename = child.getAttributeValue("name");
				Class<? extends Object> attributeclass = Class.forName(child.getAttributeValue("type"));
				Boolean notNullable = Boolean.valueOf(child.getAttributeValue("notNullable"));
				attributeNames.add(attributename);
				types.put(attributename, attributeclass);
				notNullables.put(attributename, notNullable);
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		}

	}
}
